package com.leyou.auth.service;

import com.leyou.auth.config.JwtProperties;
import com.leyou.common.auth.dto.Payload;
import com.leyou.common.auth.dto.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constants.UserTokenConstants;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.user.UserDTO;
import com.leyou.user.client.UserClient;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class AuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtProperties jwtProperties;

    public void login(String username, String password, HttpServletResponse response) {
        //1.发送请求到用户中心,查询用户
        UserDTO user = null;
        try {
            user = userClient.queryUserByUsernameAndPassword(username, password);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD, e);
        }
        //2.验证用户是否查询成功
        if (user == null) {
            throw new LyException(ExceptionEnum.INVALID_USERNAME_PASSWORD);
        }
        //3.成功:利用私钥生成JWT
        String token = JwtUtils.generateTokenExpireInMinutes(new UserInfo(user.getId(), user.getUsername(), "Guest"), jwtProperties.getPrivateKey(), UserTokenConstants.EXPIRE_MINUTES);
        //4.要把jwt写到用户的cookie中
        CookieUtils.newCookieBuilder()
                .response(response)
                .name(UserTokenConstants.COOKIE_NAME)
                .value(token)
                .domain(UserTokenConstants.DOMAIN)
                .build();

    }

    public UserInfo verifyUser(HttpServletRequest request, HttpServletResponse response) {
        try {
            //1.读取cookie
            String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
            //2.获取token信息
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
            //获取token的id,校验redis黑名单
            String id = payload.getId();
            Boolean boo = redisTemplate.hasKey(id);
            if(BooleanUtils.isTrue(boo)){
                //抛出异常,证明token无效,直接返回401
                throw new LyException(ExceptionEnum.UNAUTHORIZED);
            }
            //3.刷新token
            //3.1获取剩余有效期(过期时间-当前时间)
            long remainTime = payload.getExpiration().getTime() - System.currentTimeMillis();
            //3.2判断有效期时长是否小于某个值
            if(remainTime<20*60*1000){
                //3.3重新生成token
                JwtUtils.generateTokenExpireInMinutes(payload.getUserInfo(),jwtProperties.getPrivateKey(),UserTokenConstants.EXPIRE_MINUTES);
                //3.4覆盖以前的token
                CookieUtils.newCookieBuilder().response(response)
                        .name(UserTokenConstants.COOKIE_NAME)
                        .value(token)
                        .domain(UserTokenConstants.DOMAIN)
                        .httpOnly(true)
                        .build();
            }
            return payload.getUserInfo();
        } catch (Exception e) {
            //抛出异常,证明token无效，直接返回401
            throw new LyException(ExceptionEnum.UNAUTHORIZED);
        }
    }
@Autowired
private StringRedisTemplate redisTemplate;
    public void logout(HttpServletRequest request, HttpServletResponse response) {
        //获取token
        String token = CookieUtils.getCookieValue(request, UserTokenConstants.COOKIE_NAME);
        //解析token
        Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(),UserInfo.class);
        //获取id和剩余有效期
        String id = payload.getId();
        Long time=payload.getExpiration().getTime()-System.currentTimeMillis();
        //写入redis
        redisTemplate.opsForValue().set(id,"",time, TimeUnit.MILLISECONDS);
        //删除cookie
        CookieUtils.deleteCookie(UserTokenConstants.COOKIE_NAME,UserTokenConstants.DOMAIN,response);
    }
}
